package result

import (
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"

	"treehole/utils/xerr"
)

// HTTP响应结构
type ResponseSuccessBean struct {
	Code uint32      `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type ResponseErrorBean struct {
	Code uint32 `json:"code"`
	Msg  string `json:"msg"`
}

// 成功响应
func Success(w http.ResponseWriter, data interface{}) {
	// 设置默认message
	var msg string
	if data == nil {
		data = make(map[string]interface{})
	}
	msg = xerr.MapErrMsg(xerr.OK)

	httpx.WriteJson(w, http.StatusOK, &ResponseSuccessBean{
		Code: xerr.OK,
		Msg:  msg,
		Data: data,
	})
}

// 带自定义消息的成功响应
func SuccessWithMessage(w http.ResponseWriter, data interface{}, msg string) {
	if data == nil {
		data = make(map[string]interface{})
	}
	httpx.WriteJson(w, http.StatusOK, &ResponseSuccessBean{
		Code: xerr.OK,
		Msg:  msg,
		Data: data,
	})
}

// 错误响应
func Error(w http.ResponseWriter, errCode uint32) {
	httpx.WriteJson(w, http.StatusOK, &ResponseErrorBean{
		Code: errCode,
		Msg:  xerr.MapErrMsg(errCode),
	})
}

// 带自定义消息的错误响应
func ErrorWithMessage(w http.ResponseWriter, errCode uint32, msg string) {
	httpx.WriteJson(w, http.StatusOK, &ResponseErrorBean{
		Code: errCode,
		Msg:  msg,
	})
}

// 参数错误响应
func ParamError(w http.ResponseWriter) {
	httpx.WriteJson(w, http.StatusBadRequest, &ResponseErrorBean{
		Code: xerr.INVALID_PARAM,
		Msg:  xerr.MapErrMsg(xerr.INVALID_PARAM),
	})
}

// 未授权响应
func Unauthorized(w http.ResponseWriter) {
	httpx.WriteJson(w, http.StatusUnauthorized, &ResponseErrorBean{
		Code: xerr.UNAUTHORIZED,
		Msg:  xerr.MapErrMsg(xerr.UNAUTHORIZED),
	})
}

// 服务器错误响应
func ServerError(w http.ResponseWriter) {
	httpx.WriteJson(w, http.StatusInternalServerError, &ResponseErrorBean{
		Code: xerr.ERROR,
		Msg:  xerr.MapErrMsg(xerr.ERROR),
	})
}
